class PrayersController < ApplicationController

	before_filter :login_required, :only => [ :update, :destroy, :be_collaborator, :stop_collaborating ]

	layout 'standard'

	def index
		@prayers = Prayer.find(:all, :order => "id desc")
	end

	def create
		@prayer = Prayer.new((logged_in?) ? params[:prayer].merge!({:user_id => @signed_user.id}) : params[:prayer])
		if @prayer.save
			render :update do |page|
				page << "resetForm();"
				page << "zScrollTop(ACTIVATED_CONTAINER_ID);"
				page.insert_html :top, "prayers", :partial => 'prayer', :locals => { :prayer => @prayer }
				page.insert_html :top, "my_social_prayers", :partial => 'my_social_prayer', :locals => { :my_social_prayer => @prayer }
				# page << "fadeIn('#{dom_id(@prayer)}', 2)"
				page << "zBlink('#{dom_id(@prayer)}', 1)"
			end
		else
			render :update do |page|
				page.alert @prayer.errors.full_messages.to_sentence
			end
		end
	end

	def update
		@prayer = Prayer.find(params[:id])

		if @prayer.update_attributes(params[:prayer])
			render :update do |page|
				page.replace dom_id(@prayer), :partial => 'prayer', :locals => { :prayer => @prayer }
				page.replace "my_social_#{dom_id(@prayer)}", :partial => 'my_social_prayer', :locals => { :my_social_prayer => @prayer }
				page << "CloseLayer()"
			end
		end
	end

	def destroy
		@prayer = Prayer.find(params[:id])

		if @prayer.owned_by?(@signed_user)
			@prayer.destroy 

			render :update do |page|
				page.remove dom_id(@prayer)
				page.remove "my_social_#{dom_id(@prayer)}"
			end
		end
	end

	#
	#
	# member
	def be_collaborator
		# create collaborator
		@prayer = Prayer.find(params[:id])
		new_collaborative_prayer = @prayer.collaborative_prayers.new(:user_id => @signed_user.id)
		
		if new_collaborative_prayer.save
			render :update do |page|
				page.replace dom_id(@prayer), :partial => 'prayer', :locals => { :prayer => @prayer }
				page.insert_html :top, "my_social_prayers", :partial => 'my_social_prayer', :locals => { :my_social_prayer => @prayer }
			end
		else
			render :update do |page|
				page.alert new_collaborative_prayer.errors.full_messages.to_sentence
			end
		end
	end

	def stop_collaborating
		@prayer = Prayer.find(params[:id])
		collaborative_prayer = @prayer.collaborative_prayers.find_by_user_id(@signed_user.id)

		collaborative_prayer.destroy unless collaborative_prayer.blank?

		render :update do |page|
			page.replace dom_id(@prayer), :partial => 'prayer', :locals => { :prayer => @prayer }
			page.remove "my_social_#{dom_id(@prayer)}"
		end
	end

end
